<template>
  <div class="echart-pie-wrapper" :style="containerStyle">
    <v-chart ref="chartRef" :option="chartOption" :style="chartStyle" autoresize />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components';
import VChart from 'vue-echarts';
import { useAutoDataBinding } from '@/composables/use-data-binding';
import type { IDataBindingConfig } from '@/components/mt-edit/store/types';
import { shouldUpdateChartData } from '@/utils/shallow-equal';

// 注册ECharts组件
use([CanvasRenderer, PieChart, TitleComponent, TooltipComponent, LegendComponent]);

// 饼图数据项接口
interface PieDataItem {
  name: string;
  value: number;
}

// Props定义
interface Props {
  title?: string;
  backgroundColor?: string;
  data?: PieDataItem[];
  radius?: [string, string];
  showLabel?: boolean;
  roseType?: 'radius' | 'area' | false;
  dataBinding?: IDataBindingConfig;
}

const props = withDefaults(defineProps<Props>(), {
  title: '饼图',
  backgroundColor: 'transparent',
  data: () => [
    { name: '项目A', value: 30 },
    { name: '项目B', value: 25 },
    { name: '项目C', value: 20 },
    { name: '项目D', value: 15 },
    { name: '项目E', value: 10 }
  ],
  radius: () => ['40%', '70%'],
  showLabel: true,
  roseType: false
});

const chartRef = ref();

// 响应式属性对象（用于数据绑定）
const componentProps = ref({
  title: props.title,
  backgroundColor: props.backgroundColor,
  data: [...props.data],
  radius: props.radius,
  showLabel: props.showLabel,
  roseType: props.roseType
});

// 使用数据绑定（hide属性由render-core处理，组件跳过）
const shouldUseDataBinding =
  props.dataBinding && props.dataBinding.enabled && props.dataBinding.targetProperty !== 'hide';

const dataBinding = useAutoDataBinding(
  shouldUseDataBinding ? props.dataBinding : null,
  componentProps.value,
  (property: string, value: any) => {
    // 直接更新响应式对象的属性
    if (componentProps.value.hasOwnProperty(property)) {
      (componentProps.value as any)[property] = value;
    }
  }
);

// 数据更新已由数据绑定composable处理，这里只需要直接更新属性

// 监听props变化，同步到响应式属性对象
watch(
  () => props.data,
  (newValue, oldValue) => {
    // 使用浅比较优化，避免不必要的更新
    if (shouldUpdateChartData(newValue, oldValue)) {
      if (!shouldUseDataBinding || props.dataBinding?.targetProperty !== 'data') {
        componentProps.value.data = [...newValue];
      }
    }
  },
  { deep: false } // 关闭深度监听，依赖浅比较
);

// 容器样式
const containerStyle = computed(() => ({
  width: '100%',
  height: '100%',
  backgroundColor: componentProps.value.backgroundColor
}));

// 图表样式
const chartStyle = computed(() => ({
  width: '100%',
  height: '100%'
}));

// ECharts配置
const chartOption = computed(() => ({
  title: {
    text: componentProps.value.title,
    left: 'center',
    textStyle: {
      fontSize: 16,
      color: '#333'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    bottom: 10,
    data: componentProps.value.data.map((item) => item.name)
  },
  series: [
    {
      name: componentProps.value.title,
      type: 'pie',
      radius: props.radius,
      center: ['50%', '50%'],
      roseType: props.roseType,
      itemStyle: {
        borderRadius: 5,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: props.showLabel,
        formatter: '{b}: {c} ({d}%)'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      data: componentProps.value.data
    }
  ]
}));

// 监听props变化，同步到响应式属性对象
watch(
  () => props.title,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'title') {
        componentProps.value.title = newValue;
      }
    }
  }
);

watch(
  () => props.data,
  (newValue, oldValue) => {
    // 使用浅比较优化，避免不必要的更新
    if (shouldUpdateChartData(newValue, oldValue)) {
      if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'data') {
        componentProps.value.data = [...newValue];
      }
    }
  },
  { deep: false } // 关闭深度监听，依赖浅比较
);

watch(
  () => props.backgroundColor,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'backgroundColor') {
        componentProps.value.backgroundColor = newValue;
      }
    }
  }
);

// 提供图表实例方法
const getChartInstance = () => {
  return chartRef.value?.getEchartsInstance();
};

defineExpose({
  getChartInstance,
  componentProps
});
</script>

<style scoped>
.echart-pie-wrapper {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}
</style>
